<?php

namespace backend\models;

use yii\base\Model;
use backend\models\Admin;

/**
 * Signup form
 */
class SignupForm extends Model {

	public $username;
	public $email;
	public $password;

	/**
	 * @inheritdoc
	 */
	public function rules() {
		return [
				['username', 'filter', 'filter' => 'trim'],
				['username', 'required'],
				['username', 'unique', 'targetClass' => 'backend\models\Admin', 'message' => 'This username has already been taken.'],
				['username', 'string', 'min' => 2, 'max' => 255],
				['email', 'filter', 'filter' => 'trim'],
				['email', 'required'],
				['email', 'email'],
				['email', 'string', 'max' => 255],
				['email', 'unique', 'targetClass' => 'backend\models\Admin', 'message' => 'This email address has already been taken.'],
				['password', 'required'],
				['password', 'string', 'min' => 6],
		];
	}

	/**
	 * Signs user up.
	 *
	 * @return Admin|null the saved model or null if saving fails
	 */
	public function signup() {
		if (!$this->validate()) {
			return null;
		}

		$user = new Admin();
		$user->username = $this->username;
		$user->email = $this->email;
		$user->setPassword($this->password);
		$user->generateAuthKey();
		if ($user->save()) {
			return $user;
		} else {
			echo "<pre>";
			var_dump($user->errors);
			echo "</pre>";
			exit;
			return null;
		}
	}

	public function attributeLabels() {
		return [
			'username' => '用户名',
			'password' => '密码',
			'email' => '邮箱',
		];
	}

}
